package com.ble.lightscreen;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private Handler handler = new Handler();
    private TextView you_addr,test_show;
    private Button scan,otherset,submit,test;
    private ListView blelv;
    private EditText me1;
    private TimerTask test_task =null;
    BleLightService bls = new BleLightService();
    Conf con = new Conf();
    //所需权限
    private static final String[] REQUESTED_PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
    private static final int PERMISSION_REQ_ID = 22;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //绑定layout控件
        you_addr = findViewById(R.id.you_addr);
        blelv = findViewById(R.id.lv);
        test_show = findViewById(R.id.show);
        scan = findViewById(R.id.scan);
        otherset = findViewById(R.id.otherset);
        submit = findViewById(R.id.submit);
        test = findViewById(R.id.test);
        me1 = findViewById(R.id.mac_addr);

        //判断是否有所需权限
        if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
                //启动service服务
                Intent intent = new Intent(this,BleLightService.class);
                startService(intent);
             //显示你设置的蓝牙地址
            you_addr.setText(con.getConfigProperties("addr"));
        }
        //点击扫描显示扫描到的蓝牙
        scan.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                blelv.setAdapter(BleLightService.adapter);
            }
        });
        //设置自己蓝牙的mac地址
        submit.setOnClickListener(new View.OnClickListener() {
           public void onClick(View view) {
               if(!me1.getText().toString().equals("")){

                   con.writeDateToLocalFile("addr", me1.getText().toString());
                   //点击确定之后按设置的值开始重新计时执行
                   you_addr.setText(me1.getText().toString());
                   bls.setAddr(me1.getText().toString());
                   Toast.makeText(MainActivity.this,"请手动设置允许后台自启、高耗电等，避免杀后台",Toast.LENGTH_SHORT).show();
               }
           }
       });
        //跳转到更多配置页
        otherset.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this , SettingActivity.class);
                startActivity(i);
            }
        });
        //测试是否扫描到蓝牙及是否亮屏
        test.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Timer t = new Timer();
                   blelv.setAdapter(null);
                if (!test.getText().toString().equals("开始测试")){
                    test.setText("开始测试");
                    //取消定时器
                    t.cancel();
                    test_task.cancel();
                    test_show.setText("");
                }else {
                    Conf con = new Conf();
                    Long scantime = Long.parseLong(con.getConfigProperties("scantime"))*1000;
                    test.setText("停止测试");
                    t.schedule(test_task = new TimerTask(){
                        int i = 0;
                        public void run(){
                            i++;
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        test_show.setText("第"+i+"次扫描到"+bls.getCount()+"个蓝牙——>"+bls.getResult());
                                    }
                                });
                        }
                    }, 0,scantime/2);
                }
            }
        });
    }

    //检查是否获取到权限
    public boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,REQUESTED_PERMISSIONS,requestCode);
            return false;
        }
        return true;
    }
    //申请权限
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQ_ID: {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED
                        || grantResults[2] != PackageManager.PERMISSION_GRANTED ) {
                    Toast.makeText(this,"为正常使用请给予相应权限并手动设置允许后台自启、高耗电等",Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                }
                Intent intent = new Intent(this,BleLightService.class);
                startService(intent);
                bls.init();
                Conf con = new Conf();
                you_addr.setText(con.getConfigProperties("addr"));
                break;
            }
        }
    }
    protected void onDestroy() {
        super.onDestroy();
    }
}
